﻿using System;
using System.Collections;
using System.Windows.Forms.Layout;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Diagnostics;
using System.Globalization;

using Bots.Professionbuddy;
using Bots.Professionbuddy.BehaviorTree;
using Bots.Professionbuddy.ComponentBase;
using Bots.Professionbuddy.Dynamic;
using Bots.Professionbuddy.Localization;
using Bots.Professionbuddy.PropertyGridUtilities;
using Bots.Professionbuddy.PropertyGridUtilities.Editors;
using SmartAssembly.Delegates;
using DesmoPlugin;
//using SmartAssembly.HouseOfCards;

using Styx;
using Styx.Common;
using Styx.CommonBot;
using Styx.CommonBot.Profiles;
using Styx.TreeSharp;
using Styx.Helpers;
//using Styx.Commo
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;
using Styx.Pathing;
using Styx.Plugins;
using Bots.Professionbuddy.Components;
using Styx.CommonBot.Coroutines;

using Component = Bots.Professionbuddy.BehaviorTree;
namespace DesmoPlugin
{


    public partial class DesmoPluginCFG : Form
    {
        int selectedProf=99;
        XmlDocument doc = new XmlDocument();
        ProfessionCrafting profCrafting = new ProfessionCrafting();
        XmlHandler xmlSettings = new XmlHandler();
        AuctionPrice auctionPrice = new AuctionPrice();
        
        static string path = @"..\..\..\Temp3.xml";

        public DesmoPluginCFG()
        {
            InitializeComponent();
            //string ttest = Array.Find(xmlSettings.XmlSettings, "value");
            InitializeTreeView();
            Read_Settings();
            auctionPrice.FormClosing += new System.Windows.Forms.FormClosingEventHandler(AuctionPrice_FormClosing);
            
        }

        
        
        public void Read_Settings()
        {
                foreach (Control c in this.General.Controls)
                {
                    TextBox text = c as TextBox;
                    CheckBox check = c as CheckBox;
                    if (text != null)
                    {
                       ReadXml(text);
                       
                    }
                    if (check != null)
                    {
                        ReadXml(check);
                        
                    }    
                    
                }
                foreach (Control c in this.ProfessionSettings.Controls)
                {
                    TextBox text = c as TextBox;
                    CheckBox check = c as CheckBox;
                    IEnumerator ie = doc.SelectNodes("/Professionbuddy/SubRoutine/Settings").GetEnumerator();
                    if (text != null)
                    {
                        ReadXml(text);

                    }
                    if (check != null)
                    {
                        ReadXml(check);

                    } 

                    for (int i = 0; i < ProfEnable.Items.Count; i++)
                    {
                        ProfEnable.SelectedIndex = i;
                        for (int i2 = 0; i2 < 350; i2++)
                        {
                            if (ProfEnable.Text == XmlHandler.XmlSettings[0, i2])
                            {
                                ProfEnable.SetItemChecked(i, Boolean.Parse(XmlHandler.XmlSettings[2, i2]));
                                break;
                            }
                        }                        
                    }    

                }
                foreach (Control c in this.AuctioningSettings.Controls)
                {
                    TextBox text = c as TextBox;
                    CheckBox check = c as CheckBox;
                    Panel panel = c as Panel;
                    //string rrr = panel.Name;
                    IEnumerator ie = doc.SelectNodes("/Professionbuddy/SubRoutine/Settings").GetEnumerator();
                    
                    if (panel != null)
                    {
                        
                        foreach (Control pan in panel.Controls)
                        {
                            
                            ReadXml(pan);
                            
                        }

                    }
                    
                    if (text != null)
                    {
                        ReadXml(text);

                    }
                    if (check != null)
                    {
                        ReadXml(check);

                    } 
                }
                foreach (Control c in this.Miscellaneous.Controls)
                {
                    TextBox text = c as TextBox;
                    CheckBox check = c as CheckBox;
                    if (text != null)
                    {
                        ReadXml(text);

                    }
                    if (check != null)
                    {
                        ReadXml(check);

                    } 
                }
            
        }
        
        private void InitializeTreeView()
        {

            CraftSelection.BeginUpdate();
            

            CraftSelection.EndUpdate();
        }
        /*
        public void ReadXml(int parent_Idx, int node_Idx, string node_Name)
        {
            doc.Load(path);
            IEnumerator ie = doc.SelectNodes("/Professionbuddy/SubRoutine/Settings").GetEnumerator();
            while(ie.MoveNext())
            {
                if ((ie.Current as XmlNode).Attributes["Name"].Value != node_Name)
                { }
                else
                {                    
                    CraftSelection.Nodes[parent_Idx].Nodes[node_Idx].Checked = Boolean.Parse((ie.Current as XmlNode).Attributes["DefaultValue"].Value);
                    break;
                }                
            }
        }
        */
        /*
        public bool ReadXml(TextBox text_Box, IEnumerator ie)
        {
            doc.Load(path);
            if ((ie.Current as XmlNode).Attributes["Name"].Value != text_Box.Name)
                return false;
            else
            {
                text_Box.Text = (ie.Current as XmlNode).Attributes["DefaultValue"].Value;
                return true;
            }
        }
        public bool ReadXml(Control control, IEnumerator ie)
        {
            doc.Load(path);
            string ttp = (ie.Current as XmlNode).Attributes["Name"].Value;
            if ((ie.Current as XmlNode).Attributes["Name"].Value != control.Name)
                return false;
            else
            {
                control.Text = (ie.Current as XmlNode).Attributes["DefaultValue"].Value;
                return true;
            }
        } 
         
        */
        public void ReadXml(Control control)
        {
            for (int i = 0; i < 350; i++)
            {
                if (control.Name == XmlHandler.XmlSettings[0, i])
                {
                    control.Text = XmlHandler.XmlSettings[2, i];
                    break;
                }
            }

        }

        public void ReadXml(CheckBox check_Box)
        {

            for (int i = 0; i < 350; i++)
            {
                if (check_Box.Name == XmlHandler.XmlSettings[0, i])
                {
                    check_Box.Checked = Boolean.Parse(XmlHandler.XmlSettings[2, i]);
                    break;
                }
            }

        }

        
            
        private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                node.Checked = nodeChecked;
                if (node.Nodes.Count > 0)
                {
                    // If the current node has child nodes, call the CheckAllChildsNodes method recursively. 
                    this.CheckAllChildNodes(node, nodeChecked);
                }
            }
        }

        private void AnalyzeChildNodes()
        {
            doc.Load(path);
            foreach (TreeNode node in CraftSelection.Nodes)
            {
                /*
                int node_Count = node.Nodes.Count;
                for (int i2 = 0; i2 < node_Count; i2++)
                {
                    for (int i = 0; i < 350; i++)
                    {
                        if (node.Nodes[i2].Text == xmlSettings.XmlSettings[0, i])
                        {
                            xmlSettings.XmlSettings[0, i] = node.Nodes[i2].Checked.ToString();
                            break;
                        }
                    }
                }
                */
                int node_Count = node.Nodes.Count;
                IEnumerator ie = doc.SelectNodes("/Professionbuddy/SubRoutine/Settings").GetEnumerator();
                while (ie.MoveNext())
                {
                    for (int i2 = 0; i2 < node_Count; i2++)
                    {
                        if ((ie.Current as XmlNode).Attributes["Name"].Value == node.Nodes[i2].Text)
                        {
                            if (node.Nodes[i2].Checked == true)
                            {
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "true";
                            }
                            else
                            {
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "false";
                            }
                        }
                    }
                }
            }
            
        }

        // NOTE   This code can be added to the BeforeCheck event handler instead of the AfterCheck event. 
        // After a tree node's Checked property is changed, all its child nodes are updated to the same value. 
        private void node_AfterCheck(object sender, TreeViewEventArgs e)
        {
            // The code only executes if the user caused the checked state to change. 
            if (e.Action != TreeViewAction.Unknown)
            {
                //MessageBox.Show("You have selected " + e.Node.Text);

                if (e.Node.Nodes.Count > 0)
                {
                    /* Calls the CheckAllChildNodes method, passing in the current 
                    Checked value of the TreeNode whose checked state changed. */
                    this.CheckAllChildNodes(e.Node, e.Node.Checked);
                }
            }
        }

        private void CraftSelection_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void ProfSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedProf = ProfSelection.SelectedIndex;
            PopulateCraftWindow(selectedProf);
            //CraftSelection.Refresh();
        }

       
        private void ProfAuctSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            xmlSettings.XmlRefresh();
            MyListView.selectedProfession = (string)ProfAuctSelection.SelectedItem;
            auctGrid.GridRefresh();
            /*
            ClearPanels();
            switch ((string)ProfAuctSelection.SelectedItem)
            {
                case "Jewelcrafting":
                    {
                        panelJewelcrafting.Visible = true;
                        break;
                    }
                case "Enchanting":
                    {
                        panelEnchanting.Visible = true;
                        break;
                    }
                case "Alchemy":
                    {
                        panelAlchemy.Visible = true;
                        break;
                    }
                case "Inscription":
                    {
                        panelInscription.Visible = true;
                        break;
                    }
                case "Blacksmithing":
                    {
                        panelBlacksmithing.Visible = true;
                        break;
                    }
                case "Engineering":
                    {
                        panelEngineering.Visible = true;
                        break;
                    }
                case "Leatherworking":
                    {
                        panelLeatherworking.Visible = true;
                        break;
                    }
                case "Tailoring":
                    {
                        panelTailoring.Visible = true;
                        break;
                    }
                case "Mining":
                    {
                        panelMining.Visible = true;
                        break;
                    }
                case "Herbalism":
                    {
                        panelHerbalism.Visible = true;
                        break;
                    }
                case "Skinning":
                    {
                        panelSkinning.Visible = true;
                        //panelHerbalism.Controls.
                        break;
                    }
                case "Fishing":
                    {
                        panelFishing.Visible = true;
                        //panelHerbalism.Controls.
                        break;
                    }
                default:
                    {
                        ClearPanels();
                        break;
                    }

            }
             */ 
        }
        /*
        private void ClearPanels()
        {
            panelJewelcrafting.Visible = false;
            panelEnchanting.Visible = false;
            panelAlchemy.Visible = false;
            panelInscription.Visible = false;
            panelBlacksmithing.Visible = false;
            panelEngineering.Visible = false;
            panelLeatherworking.Visible = false;
            panelTailoring.Visible = false;
            panelMining.Visible = false;
            panelHerbalism.Visible = false;
            panelSkinning.Visible = false;
            panelFishing.Visible = false;
            
        }
        */
        public void GridRefresh()
        {
            auctGrid.Items.Clear();
            for (int i = 0; i < 350; i++)
            {
                if (XmlHandler.XmlSettings[0, i] != null)
                {
                    if (XmlHandler.XmlSettings[10, i] == (string)ProfAuctSelection.SelectedItem)
                    {
                        //if (xmlSettings.XmlSettings[0, i].Contains("valueAuctGem") || xmlSettings.XmlSettings[0, i].Contains("valueAuctDiamond"))
                        //{
                            auctGrid.Items.Add(new ListViewItem(new string[] { XmlHandler.XmlSettings[3, i], XmlHandler.XmlSettings[9, i], XmlHandler.XmlSettings[8, i], XmlHandler.XmlSettings[5, i], XmlHandler.XmlSettings[6, i], XmlHandler.XmlSettings[7, i], XmlHandler.XmlSettings[4, i], }));
                        //}
                    }
                    
                }
            }


        }

        #region PopulateCraftWindow
        public void PopulateCraftWindow (int selectedProf)
        {
            //object temp;
            CraftSelection.BeginUpdate();
            CraftSelection.Nodes.Clear();
                for (int i = 0; i < profCrafting.categoryList[selectedProf].GetLength(1); i++)
                {
                    CraftSelection.Nodes.Add(profCrafting.categoryList[selectedProf][0, i]);
                    CraftSelection.Nodes[i].ToolTipText = profCrafting.categoryList[selectedProf][1, i];

                    if (profCrafting.subCategoryList[selectedProf, i].GetLength(1) > 0)
                    {
                        for (int i2 = 0; i2 < profCrafting.subCategoryList[selectedProf, i].GetLength(1); i2++)
                        {
                            CraftSelection.Nodes[i].Nodes.Add(profCrafting.subCategoryList[selectedProf, i][0, i2]);						//Add node copying its text from strings above
                            CraftSelection.Nodes[i].Nodes[i2].ToolTipText = profCrafting.subCategoryList[selectedProf, i][1, i2];		//Add node's tooltip
                            CraftSelection.Nodes[i].Nodes[i2].Name = profCrafting.subCategoryList[selectedProf, i][2, i2];				//Add crafting spell id as node name
                            ReadXml(i, i2, CraftSelection.Nodes[i].Nodes[i2].Text);									                //Read Node check state from xml
                            CraftSelection.Nodes[i].Nodes[i2].Tag = CraftSelection.Nodes[i].Nodes[i2].Checked;
                            //temp = CraftSelection.Nodes[i].Nodes[i2].Tag;
                        }

                    }
                }
            CraftSelection.EndUpdate();            
        }
        #endregion

        void Reset_Click(object sender, EventArgs e)
        {
            doc.Load(path);           
            foreach (TreeNode node in CraftSelection.Nodes)
            {
                CheckAllChildNodes(node, false);
            }
            for (int i = 0; i < CraftSelection.GetNodeCount(false); i++ )
            {
                CraftSelection.Nodes[i].Checked = false;

            }
            foreach (int i in ProfEnable.CheckedIndices)
            {
                ProfEnable.SetItemCheckState(i, CheckState.Unchecked);
            }
            doc.Save(path);
        }

        private void SupplySet_Click(object sender, EventArgs e)
        {
            DesmoPluginSupplySet supplySet = new DesmoPluginSupplySet();
            supplySet.ShowDialog();
        }

        private void Start_Click(object sender, EventArgs e)
        {
            Apply_Click(sender, e);
            /*
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.Contains("Wow"))
                {
                    ProfileManager.LoadEmpty();
                    ProfileManager.LoadNew(path, false);

                    TreeRoot.Start();
                }
            }
             * */
        }


        #region Apply Click
        private void Apply_Click(object sender, EventArgs e)
        {
            doc.Load(path);
            AnalyzeChildNodes();
            IEnumerator ie = doc.SelectNodes("/Professionbuddy/SubRoutine/Settings").GetEnumerator();
            while (ie.MoveNext())
            {
                foreach (Control c in this.General.Controls)
                {
                    TextBox t = c as TextBox;
                    CheckBox check = c as CheckBox;
                    if (t != null)
                    {
                        if (t.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if ((t.Text) != "")
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = t.Text;
                        }
                    }
                    if (check != null)
                    {
                        if (check.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if (check.Checked)
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "true";
                            else
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "false";
                        }
                    }
                }
                foreach (Control c in this.ProfessionSettings.Controls)
                {
                    TextBox t = c as TextBox;
                    CheckBox check = c as CheckBox;
                    if (t != null)
                    {
                        if (t.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if ((t.Text) != "")
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = t.Text;
                        }
                    }
                    if (check != null)
                    {
                        if (check.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if (check.Checked)
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "true";
                            else
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "false";
                        }
                    }
                }
                foreach (Control c in this.AuctioningSettings.Controls)
                {
                    TextBox t = c as TextBox;
                    CheckBox check = c as CheckBox;
                    if (t != null)
                    {
                        if (t.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if ((t.Text) != "")
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = t.Text;
                        }
                    }
                    if (check != null)
                    {
                        if (check.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if (check.Checked)
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "true";
                            else
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "false";
                        }
                    }
                }
                foreach (Control c in this.Miscellaneous.Controls)
                {
                    TextBox t = c as TextBox;
                    CheckBox check = c as CheckBox;
                    if (t != null)
                    {
                        if (t.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if ((t.Text) != "")
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = t.Text;
                        }
                    }
                    if (check != null)
                    {
                        if (check.Name == (ie.Current as XmlNode).Attributes["Name"].Value)
                        {
                            if (check.Checked)
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "true";
                            else
                                (ie.Current as XmlNode).Attributes["DefaultValue"].Value = "false";
                        }
                    }
                }
                    
                foreach (object item in ProfEnable.Items)
                {
                    if ((ie.Current as XmlNode).Attributes["Name"].Value == item.ToString())
                        (ie.Current as XmlNode).Attributes["DefaultValue"].Value = ProfEnable.GetItemChecked(ProfEnable.Items.IndexOf(item)).ToString();
                }

            }

            
            doc.Save(path);
        }
        #endregion

        private void Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }




        private void Test_Click(object sender, EventArgs e)
        {
            int SpellID = 107640;
            int ItemID = 76568;
            string SpellName = "Fractured Sunstone";
            int testamount = 2;
            DynamicProperty<int> amount = new DynamicProperty<int>();
            amount.Code = "3";
            Craft(SpellID, SpellName, testamount);

            SellItemOnAhAction sioa = new SellItemOnAhAction();
            BuyItemFromAhAction bioa = new BuyItemFromAhAction();
            sioa.Amount = amount;
            sioa.AmountType = 0;    //  Amount = 0,  Everything = 1
            sioa.AutoFindAh = true;
            sioa.ItemID = ItemID.ToString();
            sioa.RunTime = SellItemOnAhAction.RunTimeType._12_Hours;

            sioa.Run();

            bioa.Amount = amount;
            bioa.AutoFindAh = true;
            //bioa.Run();
            
/*
            List<CastSpellAction> castSpellActionList = CastSpellAction.GetCastSpellActionList(csa2);
                CastSpellAction csa = new CastSpellAction
            //csa2.ItemId = 53845;
            DynamicProperty<int> tmp = new DynamicProperty<int>();
            DynamicProperty<int> times = new DynamicProperty<int>();
            
            tmp.Code = 53845.ToString();
            times.Code = 2.ToString();
            csa2.CheckTradeskillList();
            csa2.Entry = tmp;
            csa2.RepeatType = CastSpellAction.RepeatCalculationType.Specific;
            csa2.Repeat = times;
            csa2.Recipe.UpdateHeader();
            csa2.Recipe.Update();
            CastSpellAction csa = new CastSpellAction(csa2.Recipe, 2, CastSpellAction.RepeatCalculationType.Specific);
            csa2.Run();
            string temp = csa2.Entry.ToString();
            Logging.Write(temp);*/
        }

        public void ReadXml(int parent_Idx, int node_Idx, string node_Name)
        {
            for (int i = 0; i < 350; i++) 
            {
                if (CraftSelection.Nodes[parent_Idx].Nodes[node_Idx].Text == XmlHandler.XmlSettings[0, i])
                {
                    CraftSelection.Nodes[parent_Idx].Nodes[node_Idx].Checked = Boolean.Parse(XmlHandler.XmlSettings[2, i]);
                    break;
                }
            }
        }

        public void ReadXml(TextBox text_Box)
        {
            for (int i = 0; i < 350; i++)
            {
                if (text_Box.Name == XmlHandler.XmlSettings[0, i])
                {
                    text_Box.Text = (XmlHandler.XmlSettings[2, i]);
                    break;
                }
            }
        }

        private void SetPriceDiamond_Click(object sender, EventArgs e)
        {
            var button = sender as Button;
            auctionPrice.currentSetting = "valueAuct" + button.Name.Substring(8);
            auctionPrice.AuctionSettings(auctionPrice.currentSetting);

            
        }

        private void SetPriceGemRed_Click(object sender, EventArgs e)
        {

            string[] arr = new string[4];
            ListViewItem itm;
            //add items to ListView
            arr[0] = "product_1";
            arr[1] = "100";
            arr[2] = "10";
            itm = new ListViewItem(arr);
            auctGrid.Items.Add(itm);
        }

        private void auctGrid_DoubleClick(object sender, EventArgs e)
        {
            auctionPrice.AuctionSettings(auctGrid.FocusedItem.Text);
        }


        private void AuctionPrice_FormClosing(object sender, FormClosingEventArgs e)
        {
            auctGrid.GridRefresh();
        }
        

        
        /*
        private void Control_Added(object sender, System.Windows.Forms.ControlEventArgs e)
        {
            MessageBox.Show("The control named " + e.Control.Name + " has been added to the form.");
        }
         * */
    }
    
}
